<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use Closure;
use Illuminate\Support\Str;

class ViewRoute
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     * @throws ApiException
     */
    public function handle($request, Closure $next)
    {
        //定義控制器常量
        $route = request()->route()->action;
        if(isset($route['controller'])){
            $controller = str_replace($route['namespace'], "", $route['controller']);
            if(strpos($controller,'\\')===0){
                $controller = substr($controller,1);
            }

            $args = explode('@',$controller);
            $controller = str_replace("\\", '/',$args[0] );
            $controller = Str::replaceLast("Controller", '', $controller);
            $action  = lcfirst($args[1]);
            $namespace = trim(Str::replaceLast( basename($controller), '', $controller), "/");
            $controller = basename($controller);
            define('NAMESPACE_NAME',$namespace);
            define('CONTROLLER_NAME',basename($controller));

            //新增兼容多级
            $module_name = explode('/',$namespace);
            $module_name  = implode('/' ,array_map('lcfirst', $module_name));



            $view =  Str::snake($module_name) . '/' . Str::snake($controller) . '/' . Str::snake($action);

            define("VIEW_NAME", $view);
        }
        return $next($request);
    }

    /** 获取导航栏链接 */
//    protected function setNavbar()
//    {
//        view()->composer('layout.navbar', function ($view) {
//            $view->with('nav', Post::recent());
//        });
//    }
}
